<link id="theme" rel="stylesheet" type="text/css" href="/javascripts/extjs/resources/css/xtheme-gray.css"/>
<link id="theme" rel="stylesheet" type="text/css" href="/my_css/disabled.css"/>
<script type="text/javascript" src="/javascripts/extjs/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="/javascripts/extjs/ext-all-debug.js"></script>

<script type="text/javascript">
Ext.BLANK_IMAGE_URL = '/javascripts/extjs/resources/images/default/s.gif';

Ext.onReady(function() {
    Ext.QuickTips.init();

    var worker_id = '';
    var progress_id = '';

    var workers_listener = {
        render: function(p){
            p.on({
                    'cellclick': function(grid, rowIndex, columnIndex, e) {
                        var record = grid.getStore().getAt(rowIndex);
                        data = record.get('name');
                        worker_id= record.get('id');
                        a = border.getComponent('agenda');
                        a.setTitle('Agenda for Worker: ' + data);
                        var w = border.getComponent('panel_code').getComponent('code_id');
                        var cmdCallback= function (options, bSuccess, response) {
                          var o;
                          var showMsg = true;
                          if (true === bSuccess) {
                                  o = Ext.decode(response.responseText);
                                  if (true === o.success) {
                                    w.setValue(o.content);
                                    a1 = border.getComponent('agenda').getComponent('c').getComponent('f_1');
                                    a2 = border.getComponent('agenda').getComponent('c').getComponent('f_2')
                                    if (o.sec != null) {
                                      a2.getComponent('sec_f').setValue(o.sec);
                                      a1.getComponent('sec').setValue(true);
                                    } else {
                                      a2.getComponent('sec_f').setValue(0);
                                      a1.getComponent('sec').setValue(false)
                                    }
                                    if (o.min != null) {
                                      a2.getComponent('min_f').setValue(o.min);
                                      a1.getComponent('min').setValue(true);
                                    } else {
                                      a2.getComponent('min_f').setValue(0);
                                      a1.getComponent('min').setValue(false)
                                    }
                                    if (o.hour != null) {
                                      a2.getComponent('hour_f').setValue(o.hour);
                                      a1.getComponent('hour').setValue(true);
                                    } else {
                                      a2.getComponent('hour_f').setValue(0);
                                      a1.getComponent('hour').setValue(false)
                                    }
                                    if (o.day != null) {
                                      a2.getComponent('day_f').setValue(o.day);
                                      a1.getComponent('day').setValue(true);
                                    } else {
                                      a2.getComponent('day_f').setValue(1);
                                      a1.getComponent('day').setValue(false)
                                    }
                                    if (o.month != null) {
                                      a2.getComponent('month_f').setValue(o.month);
                                      a1.getComponent('month').setValue(true);
                                    } else {
                                      a2.getComponent('month_f').setValue(1);
                                      a1.getComponent('month').setValue(false)
                                    }
                                    if (o.weekday != null) {
                                      a2.getComponent('any_f').setValue(o.weekday);
                                      a1.getComponent('any').setValue(true);
                                    } else {
                                      a2.getComponent('any_f').setValue(0);
                                      a1.getComponent('any').setValue(false)
                                    }
                                    if (o.year != null) {
                                      a2.getComponent('year_f').setValue(o.year);
                                      a1.getComponent('year').setValue(true);
                                    } else {
                                      a2.getComponent('year_f').setValue(a2.getComponent('year_f').minValue);
                                      a1.getComponent('year').setValue(false)
                                    }
                                  } else {
                                  Ext.Msg.alert(this.errorText, o.error);
                                          }
                                  }
                       };
                       var options = {
                                url: '/scheduler/load_code'
                                        , method: 'post'
                                        , callback: cmdCallback
                                        , params: {name: data, id: worker_id}
                       };
                       conn = new Ext.data.Connection().request(options);
                    },
                    'validateedit': function(e) {
                        var name = '';
                        var old = '';
                        if (e.field == 'name') {
                            old = e.originalValue;
                            name = e.value;
                        }
                        
                        var cmdCallback= function (options, bSuccess, response) {
                          var o;
                          var showMsg = true;
                          if (true === bSuccess) {
                                  o = Ext.decode(response.responseText);
                                  if (true === o.success) {
                                  } else {
                                  
                                  Ext.Msg.alert(this.errorText, o.error);
                                  store.rejectChanges();
                                          }
                                  }
                       };
                       var options = {
                                url: '/scheduler/update'
                                        , method: 'post'
                                        , callback: cmdCallback
                                        , params: {id: e.record.get('id'), old: old, name: name}
                       };
                       if (e.field != 'id')
                        conn = new Ext.data.Connection().request(options);
                    }
                }
          );
        }
    };

    // clear code area
    var clear_code = function () {
        var panel_center = border.getComponent('panel_code');
        panel_center.getComponent('code_id').reset();
    };
    
    //clear status area
    function clear_status() {
        a = border.getComponent('agenda').getComponent('c').getComponent('f_3').getComponent('status_id');
        a.reset();
    };

    var save_code = function () {
       //record = store.getById(worker_id);
       var panel_center = border.getComponent('panel_code');
       var code = panel_center.getComponent('code_id').getValue();
       var cmdCallback= function (options, bSuccess, response) {
         var o;
         var showMsg = true;
         if (true === bSuccess) {
                  o = Ext.decode(response.responseText);
                  if (true === o.success) {
                      
                  } else {
                  Ext.Msg.alert(this.errorText, o.error);
                          }
                  }
       };
       var options = {
                url: '/scheduler/save'
                        , method: 'post'
                        , callback: cmdCallback
                        ,params: {id: worker_id, code: code}
       };
       if (worker_id != "")
           conn = new Ext.data.Connection().request(options);

    }

    function clear_event() {
        a1 = border.getComponent('agenda').getComponent('c').getComponent('f_1')
        a1.getComponent('sec').setValue(false)

        a1.getComponent('min').setValue(false)

        a1.getComponent('hour').setValue(false)

        a1.getComponent('day').setValue(false)

        a1.getComponent('month').setValue(false)

        a1.getComponent('any').setValue(false)

        a1.getComponent('year').setValue(false)
    };

    //Delete worker
    var delete_worker = function () {    
       var cmdCallback= function (options, bSuccess, response) {
         var o;
         var showMsg = true;
         if (true === bSuccess) {
                  o = Ext.decode(response.responseText);
                  if (true === o.success) {
                      record = store.getById(worker_id);
                      store.remove(record);
                      clear_code();
                      a = border.getComponent('agenda');
                      a.setTitle('Agenda for Worker: ');
                      worker_id = '';
                      clear_event();
                  } else {
                  Ext.Msg.alert(this.errorText, o.error);
                          }
                  }
       };
       var options = {
                url: '/scheduler/delete'
                        , method: 'post'
                        , callback: cmdCallback
                        ,params: {id: worker_id}
       };
       if (worker_id != "")
         conn = new Ext.data.Connection().request(options);

    };

    // this could be inline, but we want to define the Plant record
    // type so we can add records dynamically
    var Worker = Ext.data.Record.create([
           // the "name" below matches the tag name to read, except "availDate"
           // which is mapped to the tag "availability"
           {name: 'name', type: 'string'},
           {name: 'id', type: 'int'}
    ]);

    // create the Data Store
    var store = new Ext.data.Store({
        // load using HTTP
        proxy: new Ext.data.HttpProxy({url: 'my_load'}),

        // the return will be XML, so lets set up a reader
        reader: new Ext.data.JsonReader({
               // records will have a "worker" tag
               root: "rows",
               id: 'id'
           }, Worker),
        //loader: new Ext.tree.TreeLoader({ dataUrl:'/scheduler/list'})
        sortInfo:{field:'name', direction:'ASC'}
    });

    function get_status() {
       //record = store.getById(worker_id);
       var cmdCallback= function (options, bSuccess, response) {
       var o;
       var showMsg = true;
       if (true === bSuccess) {
                o = Ext.decode(response.responseText);
                if (true === o.success) {
                    a = border.getComponent('agenda').getComponent('c').getComponent('f_3').getComponent('status_id');
                    a.setValue(a.getValue() + o.status)
                } else {
                Ext.Msg.alert(this.errorText, o.error);
                        }
                }
       };
       var options = {
                url: '/scheduler/get_status'
                        , method: 'post'
                        , callback: cmdCallback
                        ,params: {id: worker_id}
       };
       if (worker_id != '')
        conn = new Ext.data.Connection().request(options);
    };

    function get_all_status() {
       //record = store.getById(worker_id);
       var cmdCallback= function (options, bSuccess, response) {
       var o;
       var showMsg = true;
       if (true === bSuccess) {
                o = Ext.decode(response.responseText);
                if (true === o.success) {
                    a = border.getComponent('agenda').getComponent('c').getComponent('f_3').getComponent('status_id');
                    a.setValue(a.getValue() + o.status)
                } else {
                Ext.Msg.alert(this.errorText, o.error);
                        }
                }
       };
       var options = {
                url: '/scheduler/get_all_status'
                        , method: 'post'
                        , callback: cmdCallback
                        ,params: {}
       };
        conn = new Ext.data.Connection().request(options);
    };

    function start_worker() {
       //record = store.getById(worker_id);
       var cmdCallback= function (options, bSuccess, response) {
       var o;
       var showMsg = true;
       if (true === bSuccess) {
                o = Ext.decode(response.responseText);
                if (true === o.success) {
                    
                } else {
                Ext.Msg.alert(this.errorText, o.error);
                        }
                }
       };
       var options = {
                url: '/scheduler/start_worker'
                        , method: 'post'
                        , callback: cmdCallback
                        ,params: {id: worker_id}
       };
       if (worker_id != "")
         conn = new Ext.data.Connection().request(options);
    };

    function stop_worker() {
       //record = store.getById(worker_id);
       var cmdCallback= function (options, bSuccess, response) {
       var o;
       var showMsg = true;
       if (true === bSuccess) {
                o = Ext.decode(response.responseText);
                if (true === o.success) {
                    
                } else {
                Ext.Msg.alert(this.errorText, o.error);
                        }
                }
       };
       var options = {
                url: '/scheduler/stop_worker'
                        , method: 'post'
                        , callback: cmdCallback
                        ,params: {id: worker_id}
       };

       if (worker_id != "")
         conn = new Ext.data.Connection().request(options);
    };

    function save_event() {
         a = border.getComponent('agenda').getComponent('c').getComponent('f_1');
         a2 = border.getComponent('agenda').getComponent('c').getComponent('f_2');
         var secc = '';
         var min = '';
         var hour = '';
         var day = '';
         var month = '';
         var any = '';
         var year = '';
         if (a.getComponent('sec').getValue())
            secc = a2.getComponent('sec_f').getValue();
         if (a.getComponent('min').getValue())
            min = a2.getComponent('min_f').getValue();
         if (a.getComponent('hour').getValue())
            hour = a2.getComponent('hour_f').getValue();
         if (a.getComponent('day').getValue())
            day = a2.getComponent('day_f').getValue();
         if (a.getComponent('month').getValue())
            month = a2.getComponent('month_f').getValue();
         if (a.getComponent('any').getValue())
            any = a2.getComponent('any_f').getValue();
         if (a.getComponent('year').getValue())
            year = a2.getComponent('year_f').getValue();
         var cmdCallback= function (options, bSuccess, response) {
         var o;
         var showMsg = true;
         if (true === bSuccess) {
                  o = Ext.decode(response.responseText);
                  if (true === o.success) {
                      
                  } else {
                  Ext.Msg.alert(this.errorText, o.error);
                          }
                  }
       };
       var options = {
                url: '/scheduler/set_event'
                        , method: 'post'
                        , callback: cmdCallback
                        ,params: {id: worker_id, sec: secc, min: min, hour: hour, day: day, month: month, any: any, year: year}
       };

       if (worker_id != "")
         conn = new Ext.data.Connection().request(options);
    };

    //add worker
    function add_worker() {
       var panel = border.getComponent('workers_panels').getComponent('workers_list');
       //alert(panel.getId());
       var cmdCallback= function (options, bSuccess, response) {
       var o;
       var showMsg = true;
       if (true === bSuccess) {
                o = Ext.decode(response.responseText);
                if (true === o.success) {
                    if (panel != null) {
                      //alert("toto ??");
                      var w = new Worker({
                        name: '',
                        id: o.id
                      });
                      w.id = o.id;
                      worker_id = o.id;
                      panel.stopEditing();
                      var yetCount = store.getCount();
                      store.insert(yetCount, w);
                      //  alert("insert Failed");
                      //store.getAt(yetCount).set("name",'toto');
                      panel.startEditing(yetCount, 0);
                    }
                } else {
                Ext.Msg.alert(this.errorText, o.error);
                        }
                }
     };
     var options = {
              url: '/scheduler/create'
                      , method: 'post'
                      , callback: cmdCallback
                      ,params: {}
     };

     conn = new Ext.data.Connection().request(options);
    };

    var set_event_listener = {
        render: function(p){
            p.on({
                    'check': function(check, checked) {
                        b = border.getComponent('agenda').getTopToolbar().items.get("button_event");
                         a = border.getComponent('agenda').getComponent('c').getComponent('f_1');
                         a2 = border.getComponent('agenda').getComponent('c').getComponent('f_2');
                         var sec = '*';
                         var min = '*';
                         var hour = '*';
                         var day = '*';
                         var month = '*';
                         var any = '*';
                         var year = '*';
                         
                         if (a.getComponent('sec').getValue())
                            sec = a2.getComponent('sec_f').getValue();
                         if (a.getComponent('min').getValue())
                            min = a2.getComponent('min_f').getValue();
                         if (a.getComponent('hour').getValue())
                            hour = a2.getComponent('hour_f').getValue();
                         if (a.getComponent('day').getValue())
                            day = a2.getComponent('day_f').getValue();
                         if (a.getComponent('month').getValue())
                            month = a2.getComponent('month_f').getValue();
                         if (a.getComponent('any').getValue())
                            any = a2.getComponent('any_f').getValue();
                         if (a.getComponent('year').getValue())
                            year = a2.getComponent('year_f').getValue();
                         var combin = sec + ' ' + min+ ' ' + hour+ ' ' + day+ ' ' + month+ ' ' + any+ ' ' + year;
                         
                         var cmdCallback= function (options, bSuccess, response) {
                         var o;
                         var showMsg = true;
                         if (true === bSuccess) {
                                  o = Ext.decode(response.responseText);
                                  if (true === o.success) {
                                    if (o.disable)
                                        b.disable();
                                    else
                                        b.enable();
                                  } else {
                                  Ext.Msg.alert(this.errorText, o.error);
                                          }
                                  }
                       };
                       var options = {
                                url: '/scheduler/disable_event'
                                        , method: 'post'
                                        , callback: cmdCallback
                                        ,params: {id: worker_id,combin: combin}
                       };

                       if (worker_id != "")
                         conn = new Ext.data.Connection().request(options);
                    }
                  }
                );
                }
    };

    var Progress = Ext.data.Record.create([
           // the "name" below matches the tag name to read, except "availDate"
           // which is mapped to the tag "availability"
           {name: 'name', type: 'string'},
           {name: 'progress',v: new Ext.ProgressBar({text:'progressbar'})}
    ]);
 
    // create the Data Store
    var progesstore = new Ext.data.Store({
        // load using HTTP
        proxy: new Ext.data.HttpProxy({url: 'progress_load'}),

        // the return will be XML, so lets set up a reader
        reader: new Ext.data.JsonReader({
               // records will have a "worker" tag
               root: "rows",
               id: 'id'
           }, Progress),
        //loader: new Ext.tree.TreeLoader({ dataUrl:'/scheduler/list'})
        sortInfo:{field:'name', direction:'ASC'}
    });

    function refresh(record) {
        alert(record.get('progress'));
    };

    function monitoring() {
        progesstore.each(refresh);
    };

    var tab_listeners = {
        render: function(p){
            p.on({
                    'tabchange': function(tab) {
                        activ_tab = tab.getActiveTab();
                        if (activ_tab.getId() == 'code_id') {
                            tab.getTopToolbar().items.get("clear").enable();
                            tab.getTopToolbar().items.get("save").enable();
                            tab.getTopToolbar().items.get("refresh").disable();
                        } else {
                            tab.getTopToolbar().items.get("clear").disable();
                            tab.getTopToolbar().items.get("save").disable();
                            tab.getTopToolbar().items.get("refresh").enable();
                        }
                     },
                     'cellclick': function(grid, rowIndex, columnIndex, e){
                        var record = grid.getStore().getAt(rowIndex);
                        progress_id = record.id;
                     }
                 }
                );
        }
    };

    //Interface
    var border = new Ext.Viewport({
        id:'border_id',
    	layout:'border',
        scope: this,
    	items:[
	       {
      		   region:"center",
                   xtype:"tabpanel",
                   activeTab:1,
                   id:'panel_code',
                   autoScroll: true, 		   
		   frame:true,
                   tbar: [{
                            text:'clear',
                            id:'clear',
                            handler: clear_code
                          },
                          {
                            text:'save',
                            id:'save',
                            handler: save_code
                          },
                          {
                            text:'refresh',
                            id:'refresh',
                            handler: monitoring
                          }
                         ],
                   listeners:tab_listeners,
      		   items:[
			  {
        		    xtype:"textarea",
                            title:"Code of the selected worker: ",
                            id:'code_id',
                            autoScroll: true,
        		    height:495,
        		    width:680

      			  },
                          new Ext.grid.EditorGridPanel({
                            title:"Monitoring",
                            id:'monitor',
                            autoScroll: true,
                            height:495,
        		    width:680,
                            store:progesstore,
                            listeners:tab_listeners,
                            cm: new Ext.grid.ColumnModel([
                                {
                                   id:'m_name',
                                   header: "Worker Name",
                                   dataIndex: 'name',
                                   sortable:true,
                                   editable:false,
                                   width: 120,
                                   editor:new Ext.form.TextField({
                                       emptyText:'Name of the worker',
                                       selectOnFocus: true
                                   })
                                },
                                {
                                   id:'m_progress',
                                   header: "Progress Bar",
                                   dataIndex: 'progress',
                                   editable:false,
                                   //sortable:true,
                                   width: 200,
                                   //editor: {
                                       //text:'Initializing...',
                                     //  xtype:'htmleditor',
                                     //  width:100
                                       //emptyText:'Name of the worker'
                                       //selectOnFocus: true
                                   //}
                                }
                            ])
                          })
                         ]
                },
	       {
		   region:"west",
                   xtype:"panel",
		   title:"Workers",
                   id:'workers_panels',
		   width:265,
		   collapsible:true,
		   titleCollapse:true,
		   items:[
			  new Ext.grid.EditorGridPanel({
  			      id:'workers_list',
                              autoScroll: true,
                              store:store,  
                              listeners: workers_listener,
                              cm: new Ext.grid.ColumnModel([                              
                                {
                                   id:'clm_name',
                                   header: "Worker Name",
                                   dataIndex: 'name',
                                   sortable:true,
                                   width: 120,
                                   editor:new Ext.form.TextField({
                                       emptyText:'Name of the worker',
                                       selectOnFocus: true
                                   })
                                },{
                                   header: "Id",
                                   id:'clm_id',
                                   sortable:true,
                                   editable:false,
                                   dataIndex: 'id',
                                   hidden:false,
                                   width: 60,
                                   editor: new Ext.form.NumberField ({
                                       allowBlank: false,
                                       allowNegative: false,
                                       maxValue: 100000
                                   })
                                }
                                ]                                                      
                              ),
                              width:260,
                              height:530,
                              autoExpandColumn:'clm_name',
                              title:'Workers Panel',
                              frame:true,
                              clicksToEdit:1,
                              tbar: [{
                                  text: 'Add',
                                  handler:add_worker
                              },
                              {
                                  text: 'Delete',
                                  handler:delete_worker
                              },
                              {
                                  text: 'Start',
                                  handler:start_worker
                              },
                              {
                                  text: 'Stop',
                                  handler:stop_worker
                              }]

			  })
			  ]
               },
               {
		   region:"south",
                   xtype:"panel",
		   title:"Agenda for Worker: ",
                   id:'agenda',
                   height:235,
                   autoScroll: true,
		   collapsible:true,
		   titleCollapse:true,
                   collapsed:true,
                   bodyStyle:'padding:5px 5px 0',
                   tbar: [{
                             text: 'Save event',
                             id:'button_event',
                             handler:save_event,
                             disabled:true
                          },
                          {
                             text: 'Status',
                             handler: get_status
                          },
                          {
                             text: 'All status',
                             handler: get_all_status
                          },
                          {
                             text: 'Clear status',
                             handler: clear_status
                          }
                   ],
		   items:[
                        {
                            layout:'column',
                            id:'c',
                            items:[
                              {
                                width:125,
                                layout: 'form',
                                id:'f_1',
                                items: [
                                  {
                                    xtype:'checkbox',
                                    fieldLabel: 'Second',
                                    listeners:set_event_listener,
                                    id: 'sec'
                                  }, 
                                  {
                                    xtype:'checkbox',
                                    fieldLabel: 'Minute',
                                    listeners:set_event_listener,
                                    id: 'min'
                                  }, 
                                  {
                                    xtype:'checkbox',
                                    fieldLabel: 'Hour',
                                    listeners:set_event_listener,
                                    id: 'hour'
                                  }, 
                                  {
                                    xtype:'checkbox',
                                    fieldLabel: 'Day',
                                    listeners:set_event_listener,
                                    id: 'day'
                                  }, 
                                  {
                                    xtype:'checkbox',
                                    fieldLabel: 'Month',
                                    listeners:set_event_listener,
                                    id: 'month'
                                  },
                                  {
                                    xtype:'checkbox',
                                    fieldLabel: 'Weekday',
                                    listeners:set_event_listener,
                                    id: 'any'
                                  }, 
                                  {
                                    xtype:'checkbox',
                                    fieldLabel: 'Year',
                                    listeners:set_event_listener,
                                    id: 'year'
                                  }
                                ]
                              },
                              {
                                width:140,
                                height:170,
                                layout: 'form',
                                id:'f_2',
                                items: [
                                  {
                                    <%=get_numberfield('sec_f', 59, 0)%>
                                  },
                                  {
                                    <%=get_numberfield('min_f', 59, 0)%>
                                  },
                                  {
                                    <%=get_numberfield('hour_f', 23, 0)%>
                                  },
                                  {
                                    <%=get_numberfield('day_f', 31, 1)%>
                                  },
                                  {
                                    <%=get_numberfield('month_f', 12, 1)%>
                                  },
                                  {
                                    <%= get_combo('any_f', false, 'weekday', 'day') %>
                                  },
                                  {
                                    xtype:'numberfield',
                                    id: 'year_f',
                                    autoHeight:true,
                                    width:120,
                                    allowNegative:false,
                                    hideLabel:true, 
                                    minValue:(new Date()).format('Y'),
                                    minText:"<%=_("The minimum value for this field is ")%>" + (new Date()).format('Y'),
                                    value:2007
                                  }
                                ]
                              },
                              {
                                width:680,
                                height:170,
                                layout: 'form',
                                id:'f_3',
                                items: [
                                  {
                                    xtype:"textarea",
                                    id:'status_id',
                                    disabled:true,
                                    disabledClass:'x-form-inline-textarea-disabled',
                                    value:'---\n Status: \n---\n\n',
                                    autoScroll: true,
                                    height:168,
                                    width:678,
                                    hideLabel:true
                                  }
                                ]
                              }
                            ]
                        }
                   ]
               }
	       ]
    });
    store.load();
    progesstore.load();
});
</script>

